<script>
import axios from "axios";
import http from "../../utils/request/request";
import UploadFile from "../RightsManagement/BaseFileMange/UploadFile";
import ShowFile from "../RightsManagement/BaseFileMange/ShowFile";
// const http = axiosObject.file;
export default {
  components: {
    UploadFile,
    ShowFile,
  },
  data() {
    return {
      itemList: [],
      showUploadFile: false,

      // 是否展示弹窗
      showFileDialog: false,
      /**由于只渲染同一个弹窗用来预览文件
       * 点击预览按钮的时候，需要知道
       * 1.字段->curProp
       * 2.文件类型->fileType
       * 3.文件路径->fileUrl
       *  */
      curProp: "",
      fileType: "",
      fileUrl: "",
      /**由于只渲染同一个弹窗用来上传视频
       * 点击上传视频按钮的时候，需要知道
       * 1.字段->curVideoProp
       */
      curVideoProp: "",
    };
  },
  props: {
    form: {
      type: Object,
    },
    labelProp: {
      type: Array,
    },
    num: {
      type: String | Number,
      default: 2,
    },
  },
  watch: {
    // 监听整个labelProp数组的变化，父组件才能动态传值
    labelProp: {
      handler(newVal, oldVal) {
        this.itemList = newVal;
      },
      immediate: true,
      deep: true,
    },
  },
  render(h) {
    const col_span = (24 / this.num) | 0; // 每一行col的大小
    const row_for = []; //几个row，用于row标签的for循环
    let i = 0;
    while (i <= this.itemList.length) {
      let row_item = this.itemList.slice(i, Number(this.num) + i);
      if (row_item.length !== 0) {
        row_for.push(row_item);
      }
      i += Number(this.num);
    }
    return (
      <div>
        {row_for.map((row) => (
          <el-row>
            {row.map((item) => (
              <el-col span={col_span}>
                <el-form-item label={item.name} prop={item.prop}>
                  {(() => {
                    if (item.select) {
                      // 处理选择框
                      return (
                        <el-select
                          value={this.form[item.prop]}
                          onChange={(value) => {
                            this.$set(this.form, item.prop, value);
                            // 获取当前的option对象
                            const curOps = item.select.options.find(
                              (option) => {
                                // 处理option
                                let opsValue = option.value;
                                if (item.select.value) {
                                  opsValue = option[item.select.value];
                                }
                                return opsValue == value;
                              }
                            );
                            // 如果传了事件，触发一下
                            item.select.change
                              ? item.select.change(value, curOps)
                              : "";
                          }}
                          placeholder={`请填写${item.name}`}
                          class="select-width"
                        >
                          {Object.prototype.toString.call(
                            item.select.options
                          ) !== "[object Array]"
                            ? console.error(
                                item.select.options + " is not a function"
                              )
                            : item.select.options.map((option) => {
                                // 处理option
                                let opsLabel = option.label;
                                let opsValue = option.value;
                                if (item.select.label) {
                                  opsLabel = option[item.select.label];
                                }
                                if (item.select.value) {
                                  opsValue = option[item.select.value];
                                }
                                return (
                                  <el-option
                                    label={opsLabel}
                                    value={opsValue}
                                  ></el-option>
                                );
                              })}
                        </el-select>
                      );
                    } else if (item.upload) {
                      // 处理上传文件
                      // 如果传upload:true则默认是图片类型
                      Object.prototype.toString.call(item.upload) ==
                      "[object Boolean]"
                        ? (item.upload = { accept: "image" })
                        : "";
                      return (
                        <el-row>
                          <el-col span={12}>
                            {item.upload.accept === "image" ? (
                              <el-upload
                                ref={`uploadRef-${item.prop}`}
                                action="http://120.77.156.205:9610/file/upload"
                                show-file-list={false}
                                file-list={
                                  this.form[item.prop]
                                    ? [
                                        {
                                          name: "file",
                                          url: this.form[item.prop],
                                        },
                                      ]
                                    : []
                                }
                                {...{
                                  props: {
                                    "before-upload": (file) => {
                                      console.log("file: ", file);
                                      if (file.type.indexOf("image/") < 0) {
                                        this.$message.warning("请上传图片类型");
                                        return false;
                                      }
                                      return true;
                                    },
                                    "on-success": (res, file) => {
                                      console.log('res: ', res);
                                      console.log('file: ', file);
                                      const url = JSON.parse(res.data).url;
                                      // this.form[item.prop] = url;
                                      this.$set(this.form, item.prop, url);
                                      this.$message.success(res.message);
                                    },
                                    "on-error": (err, file) => {
                                      this.$message.error(err.message);
                                    },
                                    "on-progress": (event, file) => {
                                      console.log("file: ", file);
                                      console.log("event: ", event);
                                    },
                                    "on-exceed": (file, fileList) => {
                                      this.$message.warning(
                                        "超出数量限制，请先删除原来文件"
                                      );
                                    },
                                  },
                                }}
                                limit={1}
                              >
                                <el-button
                                  size="small"
                                  type="primary"
                                  round
                                  icon="el-icon-plus"
                                >
                                  上传图片
                                </el-button>
                              </el-upload>
                            ) : (
                              <el-button
                                size="small"
                                type="primary"
                                round
                                icon="el-icon-plus"
                                onClick={() => {
                                  if (this.form[item.prop]) {
                                    this.$message.warning(
                                      "超出数量限制，请先删除原来文件"
                                    );
                                    return;
                                  }
                                  this.curVideoProp = item.prop;
                                  this.showUploadFile = true;
                                }}
                              >
                                上传视频
                              </el-button>
                            )}
                          </el-col>
                          <el-col span={12}>
                            {this.form[item.prop] ? (
                              <el-button
                                // slot="reference"
                                icon={`el-icon-${
                                  item.upload.accept === "image"
                                    ? "picture"
                                    : "video-camera-solid"
                                }`}
                                onClick={() => {
                                  // 显示弹窗(更新三个字段的值)
                                  this.fileType = item.upload.accept;
                                  this.curProp = item.prop;
                                  this.fileUrl = this.form[item.prop];
                                  this.showFileDialog = true;
                                }}
                              ></el-button>
                            ) : (
                              ""
                            )}
                          </el-col>
                        </el-row>
                      );
                    } else {
                      // 处理输入框
                      return (
                        <el-input
                          // vModel={this.form[item.prop]}
                          value={this.form[item.prop]}
                          onInput={(value) => {
                            // 这里非常非常非常关键！！！！！直接赋值Vue监测不到
                            this.$set(this.form, item.prop, value);
                          }}
                          placeholder={`请填写${item.name}`}
                        ></el-input>
                      );
                    }
                  })()}
                </el-form-item>
              </el-col>
            ))}
          </el-row>
        ))}
        {this.createUniqueShowFile()}
        {this.createUniqueUploadFile()}
      </div>
    );
  },
  methods: {
    // 拿到formdata数组，上传后给相应的字段赋值
    async uploadFileByFormdata(FormDataArray, field) {
      // const axiosArray = [];
      // FormDataArray.forEach((formdata) => {
      //   axiosArray.push(
      //     http.post("/file/upload", formdata, {
      //       headers: {
      //         "Content-Type": "multipart/form-data",
      //       },
      //     })
      //   );
      // });
      // let fileStr = "";
      // await axios.all(axiosArray).then(axios.spread(function(...args){
      //   // console.log('args: ', args);
      //   args.forEach((response,index)=>{
      //     const {data:res} = response;
      //     if(res.statusCode !== 20000){
      //       console.error(`第${index}个文件上传出错`);
      //     }else{
      //       let url = JSON.parse(res.data).url;
      //       fileStr
      //     }
      //   })
      // }))
      //   console.log("res: ", res);
      //   if (res.statusCode !== 20000) {
      //     console.error(res.message);
      //   } else {
      //     console.log(res.data);
      //     const data = JSON.parse(res.data);
      //     this.form[field] = data.url;
      //   }
    },
    // 创建唯一的ShowFile组件
    createUniqueShowFile() {
      return (
        <ShowFile
          dialogVisible={this.showFileDialog}
          close={() => (this.showFileDialog = false)}
          fileUrl={this.fileUrl}
          fileType={this.fileType}
          deleteFunc={async () => {
            this.$confirm(
              "此操作将永久删除该信息，请谨慎操作, 是否继续?",
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }
            )
              .then(async () => {
                if (this.fileType == "video") {
                  this.form[this.curProp] = "";
                  this.$message.success("删除成功");
                  this.showFileDialog = false;
                  return;
                }
                let url = this.form[this.curProp];
                const index = url.indexOf("/group1");
                const path = url.slice(index);
                const { data: res } = await http.delete(
                  `/file/delete?path=${path}`
                );
                if (res.statusCode !== 20000) {
                  this.$message.error(res.message);
                  console.error(res.message);
                } else {
                  this.form[this.curProp] = "";
                  this.showFileDialog = false;
                  const curRef = this.$refs[`uploadRef-${this.curProp}`];
                  curRef ? curRef.clearFiles() : "";
                  this.$message.success(res.message);
                }
              })
              .catch(() => {
                return this.$message.info("已取消删除！");
              });
          }}
        ></ShowFile>
      );
    },
    // 创建唯一的UploadFile组件 (上传视频)
    createUniqueUploadFile() {
      return (
        <UploadFile
          type="video"
          uploadSuccess={(fileStr, files) => {
            this.form[this.curVideoProp] = fileStr;
            this.$message.success("上传成功");
          }}
          isOpen={this.showUploadFile}
          closeModal={() => (this.showUploadFile = false)}
        ></UploadFile>
      );
    },
  },
};
</script>